package com.neiquan.backstage.user.web.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.Configs;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.platform_weixin.web.action.PlatformWeixinAction;
import com.neiquan.backstage.pub.bsc.dao.po.PlatformAllianceMember;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.user.UserService;

import me.chanjar.weixin.common.util.http.URIUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "userLoginAction", produces = { "text/json;charset=UTF-8" })
public class UserLoginAction {
	private static final Logger log = LoggerFactory.getLogger(PlatformWeixinAction.class);
	private static Class<?> poc = User.class;
	private static Class<?> pocM = PlatformAllianceMember.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private UserService userService;
	@Autowired
	private EntrepreneurService entrepreneurService;

	@ResponseBody
	@RequestMapping(value = "login")
	public String login(String phone, String password, Integer memberId, HttpSession session) {
		User user = userService.queryByPhone(phone, memberId);
		if (null == user) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_password_error).toJsonString();
		}
		if (!user.getPassword().equals(password)) {
			return CommonResp.buildErrorResp(BackendErrorCode.account_password_error).toJsonString();
		}
		if (user.getStatus() == 1) {
			Sessions.setLoginedUser(user, session);
		}
		Map<String, Object> map = new HashMap<>();
		Integer userId = user.getUserId();
		Integer status = user.getStatus();
		map.put("userId", userId);
		map.put("status", status);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	/**
	 * 微信绑定用户
	 * 
	 * @param phone
	 *            用户注册手机
	 * @param password
	 *            用户登陆密码
	 * @param memberId
	 *            用户区号
	 * @param session
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "autoLogin")
	public String bindinAccount(String code, Integer memberId, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		/**
		 * 向微信发起请求获取一个用户手机端的code值 回掉一个函数 参数需要一个客户端appid
		 * 
		 */
		int state = memberId;
		if (code != null) {
			return "api/userLoginAction/getOpenId?code=" + code;
		}
		PlatformAllianceMember platformAllianceMember = extraSpringHibernateTemplate.findFirstOneByPropEq(pocM, "memberId", memberId);
		String project_name = Configs.get().getString("system.project_name");
		String redirect_uri = String.format("%s/%s/api/userLoginAction/getOpenId?memberId=%d", platformAllianceMember.getWebsite(), project_name, memberId);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		url += "appid=" + platformAllianceMember.getWeixinAppId();
		url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirect_uri);
		url += "&response_type=code";
		url += "&scope=snsapi_userinfo";
		url += "&state=" + state;
		url += "#wechat_redirect";
		return "redirect:" + url;
	}

	public static void main(String[] args) {
		Integer memberId = 3;
		String project_name = Configs.get().getString("system.project_name");
		String redirect_uri = String.format("%s/%s/api/userLoginAction/getOpenId?memberId=%d", "http://x.com", project_name, memberId);
		System.out.println(redirect_uri);
		System.out.println(URIUtil.encodeURIComponent(redirect_uri));

	}

	@RequestMapping(value = "getOpenId")
	public String getOpenId(HttpServletRequest request, String code, String state, HttpSession session) throws IOException {
		String[] split = state.split(",");
		int memberId = Integer.parseInt(split[0]);
		PlatformAllianceMember platformAllianceMember = extraSpringHibernateTemplate.findFirstOneByPropEq(pocM, "memberId", memberId);
		String weixinAppId = platformAllianceMember.getWeixinAppId();
		String weixinAppSecret = platformAllianceMember.getWeixinAppSecret();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weixinAppId + "&secret=" + weixinAppSecret + "&code=" + code + "&grant_type=authorization_code";
		URL url2 = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
		connection.connect();
		InputStream inputStream = connection.getInputStream();
		Reader reader = new InputStreamReader(inputStream, "UTF-8");
		BufferedReader bufferedReader = new BufferedReader(reader);
		String str = null;
		StringBuffer sb = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			sb.append(str);
		}
		JSONObject json = JSONObject.fromObject(sb.toString());
		String openId = (String) json.get("openid");
		User entityU = userService.queryByopendId(openId, memberId);
		connection.disconnect();
		if (entityU != null) {
			Sessions.setLoginedUser(entityU, session);
			return "redirect:../../myworkaddr.jsp";
		}
		Sessions.setLoginedOpinId(openId, session);
		return "redirect:../../login.jsp?memberId=" + memberId;
	}

	/**
	 * 自动登陆判断判断openId
	 * 
	 * @param openId
	 * @param memberId
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "autoLogout")
	public String logout(String openId, int memberId, HttpSession session) {

		User user = userService.queryByopendId(openId, memberId);
		Sessions.setLoginedUser(user, session);
		return "redirect:../../bindinaccount.jsp";
	}

	@ResponseBody
	@RequestMapping(value = "userLogout")
	public String logout(HttpSession session) {
		Sessions.removeLoginedUser(session);
		return CommonResp.buildSuccessResp().toJsonString();
	}
}
